package com.jeesite.modules.rt.tp.service;

import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.component.CatchService;
import com.jeesite.modules.mo.service.MoneyService;
import com.jeesite.modules.rt.dao.RtDeviceDao;
import com.jeesite.modules.rt.dao.RtErrorDao;
import com.jeesite.modules.rt.dto.RouterParameter;
import com.jeesite.modules.rt.entity.*;
import com.jeesite.modules.rt.job.DeviceService;
import com.jeesite.modules.rt.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.text.ParseException;
import java.util.*;

import static org.bouncycastle.asn1.cmc.CMCStatus.success;

/**
 * 领雾业务处理
 */
@Service
@Slf4j
public class LingwuService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${router.api.appId}")
    private String appId;

    @Value("${router.api.secret}")
    private String secret;
    @Autowired
    private RtDeviceService rtDeviceService;
    @Autowired
    private CatchService catchService;
    @Autowired
    private RtDeviceDao rtDeviceDao;
    @Autowired
    private RtDeviceLineService rtDeviceLineService;
    @Autowired
    private RtDeviceBohaoService rtDeviceBohaoService;
    @Autowired
    private RtDeviceHardwareService rtDeviceHardwareService;
    @Autowired
    private RtDevicePaoliangService rtDevicePaoliangService;
    @Autowired
    private RtDeviceShouyiService rtDeviceShouyiService;
    @Autowired
    private MoneyService moneyService;
    @Autowired
    private RtDeviceUpdownService rtDeviceUpdownService;
    @Autowired
    private RtErrorService rtErrorService;
    @Autowired
    private RtErrorDao rtErrorDao;
    @Autowired
    private DeviceService deviceService;

    /**
     * 同步设备报警信息
     */
    public void synErrorInfo(){

        //清空表
        rtErrorDao.cleanTable();

        int pageNo = 0;
        int pageSize = 100;
        long count = rtDeviceDao.findCount(new RtDevice());
        long l = count / pageSize;
        do {
            List<RtDevice> devicePage = rtDeviceDao.getDevicePage(pageNo * pageSize, pageSize);
            String sns = "";
            for(RtDevice rtDevice:devicePage){
                String sn = rtDevice.getSn();
                sns += ","+sn;
            }
            if(StringUtils.isNotEmpty(sns)) {
                sns = sns.substring(1);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("sn", sns);
                Object jsonObjectResult = postJOSN("https://openapi.linkfog.cn/openapi/v2/deviceAlarmInfo",jsonObject);
                if(jsonObjectResult!=null){
                    JSONArray jsonObjectArray = (JSONArray) jsonObjectResult;
                    if(jsonObjectArray!=null && jsonObjectArray.size()>0){
                        for(int i = 0;i<jsonObjectArray.size();i++){
                            JSONObject jsonObject1 = jsonObjectArray.getJSONObject(i);
                            RtError rtError = jsonObject1.toJavaObject(RtError.class);
                            rtError.setCreateTime(new Date());
                            rtErrorService.save(rtError);
                        }
                    }
                }
            }
            pageNo++;
        }while (l>=pageNo);

    }

    /**
     * 请求领雾数据
     * @param url
     * @param jsonObject
     * @return
     */
    public String postJOSNBase(String url,JSONObject jsonObject){
        String jsonStr = JSONObject.toJSONString(jsonObject);
        String signRoot = appId + secret + jsonStr;
        String sign = DigestUtil.sha256Hex(Base64.getEncoder().encodeToString(signRoot.getBytes(Charset.defaultCharset())));
        HttpHeaders headers = new HttpHeaders();
        headers.set("comtent-type", MediaType.APPLICATION_JSON_VALUE);
        headers.set("appid", appId);
        headers.set("sign", sign);
        log.info(url+"接口参数："+jsonObject.toJSONString());
        HttpEntity<String> jsonEntity = new HttpEntity<String>(jsonObject.toJSONString(), headers);
        String resultStr = restTemplate.postForObject(url,jsonEntity,String.class);
        log.info("接口返回："+resultStr);
        return resultStr;

    }

    /**
     * 请求领雾数据
     * @param url
     * @param jsonObject
     * @return
     */
    public Object postJOSN(String url,JSONObject jsonObject){
        String resultStr = postJOSNBase(url, jsonObject);
        JSONObject jsonObjectResult = JSONObject.parseObject(resultStr);
        if(jsonObjectResult.getIntValue("code")==200){
            return jsonObjectResult.get("result");
        }else{
            //todo 记录数据请求异常
            return null;
        }
    }

    /**
     *同步拨号信息
     */
    @Async("taskExecutor3")
    public void synBohaoInfo(){
        int pageNo = 0;
        int pageSize = 200;
        long count = rtDeviceDao.findCount(new RtDevice());
        long l = count / pageSize;
        do{
            List<RtDevice> devicePage = rtDeviceDao.getDevicePage(pageNo * pageSize, pageSize);
            String sns = "";
            for(RtDevice rtDevice:devicePage){
                String sn = rtDevice.getSn();
                sns += ","+sn;
            }
            if(StringUtils.isNotEmpty(sns)) {
                sns = sns.substring(1);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("sn", sns);
                Object jsonObjectResult = postJOSN("https://openapi.linkfog.cn/openapi/v3/queryDialInfo",jsonObject);
                if(jsonObjectResult!=null){
                    JSONArray jsonObjectArray = (JSONArray) jsonObjectResult;
                    if(jsonObjectArray!=null && jsonObjectArray.size()>0){
                        for(int i=0;i<jsonObjectArray.size();i++){
                            JSONObject deviceJSON = jsonObjectArray.getJSONObject(i);
                            String sn = deviceJSON.getString("sn");
                            String uploadSpeed = deviceJSON.getString("uploadSpeed");
                            RtDevice deviceBySn = rtDeviceService.getDeviceBySn(sn);
                            if(StringUtils.isNotEmpty(uploadSpeed)){
                                if(deviceBySn!=null){
                                    deviceBySn.setUploadSpeed(uploadSpeed);
                                    rtDeviceService.save(deviceBySn);
                                }
                            }
                            JSONArray vlanListJSONArray = deviceJSON.getJSONArray("vlanList");
                            if(vlanListJSONArray!=null && vlanListJSONArray.size()>0){
                                rtDeviceBohaoService.delBySn(sn);
                                for(int j=0;j<vlanListJSONArray.size();j++){
                                    JSONObject vlanJSON = vlanListJSONArray.getJSONObject(j);
                                    RtDeviceBohao rtDeviceBohao = vlanJSON.toJavaObject(RtDeviceBohao.class);
                                    rtDeviceBohao.setSn(sn);
                                    rtDeviceBohao.setDeviceId(deviceBySn.getId());
                                    rtDeviceBohaoService.save(rtDeviceBohao);
                                }
                            }
                        }
                    }
                }
            }

            pageNo++;
        }while (l>=pageNo);

    }

    /**
     * 同步最新网络信息
     */
    @Async("taskExecutor3")
    public void flowDeviceNetInfo(){
        //刷新开始时间
        String lineRefreshTime = catchService.get(RouterParameter.CATCH_ROUTER_DEVICE_LINE_REFRESH_TIME);

        Date refreshDate = new Date();

        if(StringUtils.isNotEmpty(lineRefreshTime)){
            Long l = Long.valueOf(lineRefreshTime);
            refreshDate = new Date(l);
        }else{
            catchService.add(RouterParameter.CATCH_ROUTER_DEVICE_LINE_REFRESH_TIME,String.valueOf(refreshDate.getTime()));
        }
        List<RtDevice> noRefreshLineDataList = rtDeviceDao.findNoRefreshLineData(refreshDate);
        if(noRefreshLineDataList.size()<300){
            catchService.delete(RouterParameter.CATCH_ROUTER_DEVICE_LINE_REFRESH_TIME);
        }
        String sns = "";
        for(RtDevice rtDevice:noRefreshLineDataList){
            String sn = rtDevice.getSn();
            sns += ","+sn;
        }
        if(StringUtils.isNotEmpty(sns)){
            sns = sns.substring(1);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("sn", sns);
            Object jsonObjectResult = postJOSN("https://openapi.linkfog.cn/openapi/v4/flowDeviceNetInfo",jsonObject);
            if(jsonObjectResult==null){
                return;
            }
            JSONArray records = (JSONArray)jsonObjectResult;
            //解析数据
            for(int i=0;i<records.size();i++){
                JSONObject record = records.getJSONObject(i);
                String sn = record.getString("sn");
                RtDevice deviceBySn = rtDeviceService.getDeviceBySn(sn);
                if(deviceBySn!=null){
                    record.put("deviceId",deviceBySn.getId());
                    rtDeviceLineService.jsonToDeviceLine(record);
                }
            }
        }

    }


    /**
     * 设置区域限制
     */
    public JSONObject setQuyuxianzhi(String sn,String type){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("sn", sn);
        jsonObject.put("type", Integer.valueOf(type));
        String str = postJOSNBase("https://openapi.linkfog.cn/openapi/v4/modifyDeviceLimitArea",jsonObject);

        return JSONObject.parseObject(str);
    }


    /**
     * 收益查询
     */
    @Async("taskExecutor3")
    public void synShouyiInfo(String startDate){
        int page = 1;
        int pageSize = 200;
        long totalPage = 0;
        do{
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("pageNo", page);
            jsonObject.put("pageSize", pageSize);
            jsonObject.put("workDate", startDate);
            Object jsonObjectResult = postJOSN("https://openapi.linkfog.cn/openapi/v2/queryDeviceRevenueByPage",jsonObject);
            if(jsonObjectResult!=null){
                JSONObject jsonObjectResultPage = (JSONObject)jsonObjectResult;
                totalPage = jsonObjectResultPage.getLong("totalPage");
                JSONArray jsonArray = jsonObjectResultPage.getJSONArray("records");
                if(jsonArray!=null && jsonArray.size()>0){
                    for(int i=0;i<jsonArray.size();i++){
                        JSONObject record = jsonArray.getJSONObject(i);
                        String sn = record.getString("sn");
                        RtDeviceShouyi rtDeviceShouyi = rtDeviceShouyiService.getPaoliangBySnDate(sn,startDate);
                        RtDeviceShouyi rtDeviceShouyiJson = record.toJavaObject(RtDeviceShouyi.class);
                        rtDeviceShouyiJson.setProvinceCity(record.getString("province")+record.getString("city"));
                        if(rtDeviceShouyi!=null){
                            rtDeviceShouyiJson.setId(rtDeviceShouyi.getId());
                            rtDeviceShouyiJson.setIsNewRecord(false);
                        }
                        rtDeviceShouyiJson.setUpdateTime(new Date());
                        rtDeviceShouyiService.save(rtDeviceShouyiJson);
                        //同步用户收益
                        try{
                            moneyService.synUserShouyi(sn,rtDeviceShouyiJson.getWorkDate(),rtDeviceShouyiJson.getAmount());
                        }catch (Exception e){
                            log.error("同步用户收益异常:sn="+sn,e);
                        }

                        RtDevicePaoliang paoliangBySnDate = rtDevicePaoliangService.getPaoliangBySnDate(sn, startDate);
                        if(paoliangBySnDate!=null){
                            paoliangBySnDate.setAmount(record.getBigDecimal("amount"));
                            rtDevicePaoliangService.save(paoliangBySnDate);
                        }

                        String isProvince = rtDeviceShouyiJson.getIsProvince();

                        if(StringUtils.isNotEmpty(isProvince)){
                            RtDevice deviceBySn = rtDeviceService.getDeviceBySn(sn);
                            deviceBySn.setQuyuxianzhi(isProvince.equals("是")?"2":"0");
                            rtDeviceService.save(deviceBySn);
                        }
                    }
                }
            }
            page++;
        }while (page<=totalPage);
    }

    /**
     * 跑量查询
     */
    @Async("taskExecutor3")
    public void synPaoliangInfo(String startDate,String endDate){
        int page = 0;
        int pageSize = 100;
        int total = new Long(rtDeviceDao.findCount(new RtDevice())).intValue();
        do{
            String sns = "";
            List<RtDevice> noRefreshLineDataList = rtDeviceDao.getDevicePage(page*pageSize,pageSize);
            int size = noRefreshLineDataList.size();
            if(size>0){
                for(RtDevice rtDevice:noRefreshLineDataList){
                    String sn = rtDevice.getSn();
                    sns+=","+sn;
                }
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("sn", sns.substring(1));
                jsonObject.put("startDate", startDate);
                jsonObject.put("endDate", endDate);
                Object jsonObjectResult = postJOSN("https://openapi.linkfog.cn/openapi/queryBandwidth",jsonObject);
                if(jsonObjectResult!=null){
                    JSONArray jsonObjectArray = (JSONArray) jsonObjectResult;
                    if(jsonObjectArray!=null && jsonObjectArray.size()>0){
                        for(int i=0;i<jsonObjectArray.size();i++){
                            JSONObject paoliangJSON = jsonObjectArray.getJSONObject(i);
                            String snOne = paoliangJSON.getString("sn");
                            String workDate = paoliangJSON.getString("workDate");
                            RtDevicePaoliang paoliangBySnDate = rtDevicePaoliangService.getPaoliangBySnDate(snOne, workDate);
                            RtDevicePaoliang rtDevicePaoliang = paoliangJSON.toJavaObject(RtDevicePaoliang.class);
                            rtDevicePaoliang.setProvinceCity(paoliangJSON.getString("province")+paoliangJSON.getString("city"));
                            if(paoliangBySnDate!=null){
                                rtDevicePaoliang.setAmount(paoliangBySnDate.getAmount());
                                rtDevicePaoliang.setId(paoliangBySnDate.getId());
                                rtDevicePaoliang.setIsNewRecord(false);
                            }
                            rtDevicePaoliangService.save(rtDevicePaoliang);
                        }
                    }
                }
            }
            page++;
        }while (page*pageSize <= total);


    }

    /**
     * 更新硬件信息
     */
    @Async("taskExecutor3")
    public void synYingjianInfo(String startDate,String endDate){

        Map<String,RtDeviceHardware> mapYingpan = new HashMap<>();

        int page = 0;
        int pageSize = 200;
        int total = new Long(rtDeviceDao.findCount(new RtDevice())).intValue();
        do {
            String sns = "";
            List<RtDevice> noRefreshLineDataList = rtDeviceDao.getDevicePage(page * pageSize, pageSize);
            int size = noRefreshLineDataList.size();
            if (size > 0) {
                for (RtDevice rtDevice : noRefreshLineDataList) {
                    String sn = rtDevice.getSn();
                    sns += "," + sn;
                }


                //硬盘使用率
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("sn", sns.substring(1));
                jsonObject.put("queryDate", DateUtils.getDate());
                jsonObject.put("startTime", startDate);
                jsonObject.put("endTime", endDate);
                Object jsonObjectResult = postJOSN("https://openapi.linkfog.cn/openapi/v2/flowDeviceHardwareFrequencyInfo", jsonObject);
                if (jsonObjectResult != null) {
                    JSONObject jsonObjectResultOne = (JSONObject) jsonObjectResult;
                    if (jsonObjectResultOne != null) {
                        Set<String> strings = jsonObjectResultOne.keySet();
                        for (String sn : strings) {
                            JSONArray jsonArray = jsonObjectResultOne.getJSONArray(sn);
                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject jsonObjectOne = jsonArray.getJSONObject(i);
                                double cpuUsedRate = jsonObjectOne.getDouble("cpuUsedRate");
                                double memUsedRate = jsonObjectOne.getDouble("memUsedRate");

                                RtDeviceHardware rtDeviceHardware = mapYingpan.get(sn);
                                if(rtDeviceHardware == null){
                                    rtDeviceHardware = rtDeviceHardwareService.findOneBySn(sn);
                                    if (rtDeviceHardware == null) {
                                        rtDeviceHardware = new RtDeviceHardware();
                                    }
                                }

                                rtDeviceHardware.setCpuUsedRate(cpuUsedRate);
                                rtDeviceHardware.setMemUsedRate(memUsedRate);

                                mapYingpan.put(sn, rtDeviceHardware);
                            }
                        }
                    }
                }

                //数据盘信息
                Object jsonObjectData = postJOSN("https://openapi.linkfog.cn/openapi/v2/flowDeviceDiskInfo", jsonObject);
                if (jsonObjectData != null) {
                    JSONObject jsonObjectResultOne = (JSONObject) jsonObjectData;
                    if (jsonObjectResultOne != null) {
                        Set<String> snList = jsonObjectResultOne.keySet();
                        for (String sn : snList) {
                            JSONArray jsonArray = jsonObjectResultOne.getJSONArray(sn);
                            if (jsonArray != null && jsonArray.size() > 0) {
                                JSONObject jsonObject1 = jsonArray.getJSONObject(0);
                                RtDeviceHardware rtDeviceHardware = mapYingpan.get(sn);
                                if(rtDeviceHardware == null){
                                    rtDeviceHardware = rtDeviceHardwareService.findOneBySn(sn);
                                    if (rtDeviceHardware == null) {
                                        rtDeviceHardware = new RtDeviceHardware();
                                    }
                                }
                                rtDeviceHardware.setName(jsonObject1.getString("name"));
                                rtDeviceHardware.setRawait(jsonObject1.getDouble("rawait").toString());
                                rtDeviceHardware.setIoutil(jsonObject1.getDouble("ioutil").toString());
                                rtDeviceHardware.setWawait(jsonObject1.getDouble("wawait").toString());
                                rtDeviceHardware.setSerial(jsonObject1.getString("serial"));
                                rtDeviceHardware.setIsCache(jsonObject1.getString("isCache"));
                                rtDeviceHardware.setType(jsonObject1.getString("type"));
                                rtDeviceHardware.setTemperature(jsonObject1.getDouble("temperature").toString());
                                rtDeviceHardware.setTotal(jsonObject1.getDouble("total").toString());
                                rtDeviceHardware.setUsed(jsonObject1.getDouble("used").toString());
                                rtDeviceHardware.setIps(jsonObject1.getDouble("ips").toString());
                                rtDeviceHardware.setOps(jsonObject1.getDouble("ops").toString());
                                mapYingpan.put(sn, rtDeviceHardware);

                            }

                        }
                    }
                }
            }
            page++;
        }while (page*pageSize <= total);

        //硬件信息
        JSONObject jsonObjectYingjian = new JSONObject();
        Object jsonObjectResultYingjian = postJOSN("https://openapi.linkfog.cn/openapi/v2/queryDeviceDetailInfo", jsonObjectYingjian);
        if (jsonObjectResultYingjian != null) {
            JSONArray jsonArrayYingjian = (JSONArray) jsonObjectResultYingjian;
            if (jsonArrayYingjian != null) {
                for (int i = 0; i < jsonArrayYingjian.size(); i++) {
                    JSONObject jsonObjectOne = jsonArrayYingjian.getJSONObject(i);
                    String sn = jsonObjectOne.getString("sn");
                    Double memTotal = jsonObjectOne.getDouble("memTotal");
                    Integer cpuCore = jsonObjectOne.getInteger("cpuCore");

                    RtDeviceHardware rtDeviceHardware = mapYingpan.get(sn);
                    if(rtDeviceHardware == null){
                        rtDeviceHardware = rtDeviceHardwareService.findOneBySn(sn);
                        if (rtDeviceHardware == null) {
                            rtDeviceHardware = new RtDeviceHardware();
                        }
                    }
                    rtDeviceHardware.setMemTotal(memTotal.toString());
                    rtDeviceHardware.setCpuCore(cpuCore.toString());
                    mapYingpan.put(sn, rtDeviceHardware);

                }
            }
        }

        //系统盘信息
        JSONObject jsonObjectXitongpan = new JSONObject();
        Object jsonObjectResultXitongpan = postJOSN("https://openapi.linkfog.cn/openapi/v2/deviceSystemDiskSize", jsonObjectXitongpan);
        if (jsonObjectResultXitongpan != null) {
            JSONArray jsonArrayYingjian = (JSONArray) jsonObjectResultXitongpan;
            if (jsonArrayYingjian != null) {
                for (int i = 0; i < jsonArrayYingjian.size(); i++) {
                    JSONObject jsonObjectOne = jsonArrayYingjian.getJSONObject(i);
                    String sn = jsonObjectOne.getString("sn");
                    Double totalXi = jsonObjectOne.getDouble("total");
                    Double used = jsonObjectOne.getDouble("used");

                    RtDeviceHardware rtDeviceHardware = mapYingpan.get(sn);
                    if(rtDeviceHardware == null){
                        rtDeviceHardware = rtDeviceHardwareService.findOneBySn(sn);
                        if (rtDeviceHardware == null) {
                            rtDeviceHardware = new RtDeviceHardware();
                        }
                    }
                    rtDeviceHardware.setXtTotal(totalXi.toString());
                    rtDeviceHardware.setXtUsed(used.toString());
                    mapYingpan.put(sn, rtDeviceHardware);

                }
            }
        }

        Set<String> strings = mapYingpan.keySet();
        for (String sn : strings) {
            RtDeviceHardware rtDeviceHardware = mapYingpan.get(sn);
            if(rtDeviceHardware != null){
                rtDeviceHardware.setSn(sn);
                rtDeviceHardware.setUpdateTime(new Date());
                rtDeviceHardwareService.save(rtDeviceHardware);
            }
        }
    }


    /**
     * 更新上行带宽
     */
    @Async("taskExecutor3")
    public void synUpDownFlow(){
        //刷新开始时间
        String lineRefreshTime = catchService.get(RouterParameter.CATCH_ROUTER_DEVICE_UPDOWN_REFRESH_TIME);

        Date refreshDate = new Date();

        if(StringUtils.isNotEmpty(lineRefreshTime)){
            Long l = Long.valueOf(lineRefreshTime);
            refreshDate = new Date(l);
        }else{
            catchService.add(RouterParameter.CATCH_ROUTER_DEVICE_UPDOWN_REFRESH_TIME,String.valueOf(refreshDate.getTime()));
        }
        List<RtDevice> noRefreshLineDataList = rtDeviceDao.findNoUpRefreshLineData(refreshDate);
        if(noRefreshLineDataList.size()<300){
            catchService.delete(RouterParameter.CATCH_ROUTER_DEVICE_UPDOWN_REFRESH_TIME);
        }
        String sns = "";
        for(RtDevice rtDevice:noRefreshLineDataList){
            String sn = rtDevice.getSn();
            sns += ","+sn;
        }
        if(StringUtils.isNotEmpty(sns)){
            sns = sns.substring(1);
            //上行带宽
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("sn", sns);
            String endTime = DateUtils.getTime();
            String startTime = DateUtils.getDate("HH:mm:ss", -20, Calendar.MINUTE);
            jsonObject.put("startTime",startTime);
            jsonObject.put("endTime",endTime);
            Object jsonObjectResult = postJOSN("https://openapi.linkfog.cn/openapi/fireTiger/flowBandwidthByMinute",jsonObject);
            if(jsonObjectResult!=null){
                JSONObject recordsDvice = (JSONObject)jsonObjectResult;
                noRefreshLineDataList.forEach(rtDevice->{
                    String sn = rtDevice.getSn();
                    JSONArray jsonArray = recordsDvice.getJSONArray(sn);
                    if(jsonArray!=null && jsonArray.size()>0){
                        JSONObject jsonObjectLast = jsonArray.getJSONObject(jsonArray.size() - 1);
                        Double bandwidth = jsonObjectLast.getDouble("bandwidth");
                        rtDevice.setFlow(bandwidth.toString());
                        try {
                            rtDevice.setUpRefreshTime(DateUtils.parseDate(jsonObjectLast.getString("timeSlice"),"yyyy-MM-dd HH:mm:ss"));
                        } catch (ParseException e) {

                        }
                    }
                });
            }
            //下行带宽
            Object jsonObjectResultDown = postJOSN("https://openapi.linkfog.cn/openapi/fireTiger/flowDownloadBandwidthByMinute",jsonObject);
            if(jsonObjectResultDown!=null){
                JSONObject recordsDvice = (JSONObject)jsonObjectResultDown;
                noRefreshLineDataList.forEach(rtDevice->{
                    String sn = rtDevice.getSn();
                    JSONArray jsonArray = recordsDvice.getJSONArray(sn);
                    if(jsonArray!=null && jsonArray.size()>0){
                        JSONObject jsonObjectLast = jsonArray.getJSONObject(jsonArray.size() - 1);
                        Double bandwidth = jsonObjectLast.getDouble("downloadBandwidth");
                        rtDevice.setFlowDownload(bandwidth.toString());
                        try {
                            rtDevice.setDownRefreshTime(DateUtils.parseDate(jsonObjectLast.getString("timeSlice"),"yyyy-MM-dd HH:mm:ss"));
                        } catch (ParseException e) {

                        }
                    }
                });
            }

            noRefreshLineDataList.forEach(rtDevice->{
//                log.info("下行带宽："+rtDevice.getFlowDownload());
//                log.info("上行带宽："+rtDevice.getFlow());
                RtDeviceUpdown rtDeviceUpdown = new RtDeviceUpdown();
                rtDeviceService.save(rtDevice);
                if(StringUtils.isNotEmpty(rtDevice.getFlow())){
                    rtDeviceUpdown.setSn(rtDevice.getSn());
                    rtDeviceUpdown.setUp(rtDevice.getFlow());
                    rtDeviceUpdown.setDown(rtDevice.getFlowDownload());
                    rtDeviceUpdown.setWorkDate(new Date());
                    rtDeviceUpdownService.save(rtDeviceUpdown);
                }
            });

        }
    }

    /**
     * 批量更新设备数据
     */
    @Async("taskExecutor3")
    public void synDeviceData(){
        int pageNo = 1;//当前页数
        int totalPage = 1;//总页数
        do{
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("pageNo", String.valueOf(pageNo));
            jsonObject.put("pageSize", 200);
            Object jsonObjectResult = postJOSN("https://openapi.linkfog.cn/openapi/common/queryDeviceByPage",jsonObject);
            if(jsonObjectResult==null){
                return;
            }
            JSONObject jsonObjectData = (JSONObject)jsonObjectResult;
            totalPage = jsonObjectData.getIntValue("totalPage");
            //解析数据
            JSONArray records = jsonObjectData.getJSONArray("records");
            for(int i=0;i<records.size();i++){
                JSONObject record = records.getJSONObject(i);
                rtDeviceService.jsonToDevice(record);
            }

            pageNo++;
        }while (pageNo<=totalPage);

    }





    public static void main(String[] args) {
//        String appId = "10377";
//        String secret = "8c043b3076e7428981e1230d28c11956";
//        String url = "https://openapi.linkfog.cn/openapi/common/queryDeviceByPage";
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("pageSize", 20);
//        String jsonStr = JSONObject.toJSONString(jsonObject);
//        String signRoot = appId + secret + jsonStr;
//        String sign = DigestUtil.sha256Hex(Base64.getEncoder().encodeToString(signRoot.getBytes(Charset.defaultCharset())));
//        HttpHeaders headers = new HttpHeaders();
//        headers.set("comtent-type", MediaType.APPLICATION_JSON_VALUE);
//        headers.set("appid", appId);
//        headers.set("sign", sign);
//        HttpEntity<String> jsonEntity = new HttpEntity<String>(jsonObject.toJSONString(), headers);
//        RestTemplate restTemplate = new RestTemplate();
//        System.out.println(restTemplate.postForObject(url,jsonEntity,String.class));
    }
}
